package com.etoak.commons.utils;

import org.apache.commons.collections4.CollectionUtils;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Set;

public class ValidatorUtil {

    //Java Bean的校验器
    public static final Validator validator;

    static {
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        validator = factory.getValidator();
    }

    /**
     * 实现对java bean的校验
     * @param obj
     */
    public static void validate(Object obj){

        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(obj);
        if(CollectionUtils.isNotEmpty(constraintViolations)){
            StringBuffer errorBuf = new StringBuffer();
            constraintViolations.forEach(violation ->{
                //对象中被校验的字段
                String field = violation.getPropertyPath().toString();
                //错误消息
                String message = violation.getMessage();
                errorBuf.append(field).append(message).append(";");
            });
            //抛出异常
            throw new RuntimeException(errorBuf.toString());
        }
    }
}
